__file__ = 'A02.py'
__author__ = 'Jerry Liu'
__date__ = '2016-04-13'

"""
    问题：将 0001 题生成的 200 个激活码（或者优惠券）保存到 MySQL 关系型数据库中
    安装pillow库：
    1、http://www.lfd.uci.edu/~gohlke/pythonlibs/下载 mysql_connector_python-2.0.4-py2.py3-none-any.whl
    2、使用命令pip install mysql_connector_python-2.0.4-py2.py3-none-any.whl进行安装
"""
import mysql.connector
import random

def save(num):

    conn = mysql.connector.connect(host='localhost', user='root', password='123456', database='ShowMeTheCode')
    cursor = conn.cursor()
    for i in range(num):
        choiceCode = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C']
        # 随机生成10个数字
        code = [random.choice(choiceCode) for i in range(10)]
        sql = 'insert into code(code) values(%s)'
        code = ''.join(code)
        try:
            cursor.execute(sql, [code])
        except BaseException as e:
            print(e)
            break

    # 提交并关闭连接
    conn.commit()
    cursor.close()
    conn.close()
    print('完成')

if __name__ == '__main__':
    save(200)
